package delete_self

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
)

func DeleteSelf() {
	fmt.Println("Hello, world!")

	// 获取当前执行文件的路径
	exePath, err := os.Executable()
	if err != nil {
		fmt.Println("Error getting executable path:", err)
		return
	}

	// 创建一个临时批处理文件或脚本来删除自身
	var cmd *exec.Cmd
	if runtime.GOOS == "windows" {
		// Windows下的删除命令
		batchFile := filepath.Join(os.TempDir(), "delete_self.bat")
		err = os.WriteFile(batchFile, []byte(fmt.Sprintf("timeout /t 1 >nul\n del \"%s\"", exePath)), 0644)
		if err != nil {
			fmt.Println("Error creating batch file:", err)
			return
		}
		cmd = exec.Command("cmd", "/C", batchFile)
	} else {
		// Unix/Linux下的删除命令
		scriptFile := filepath.Join(os.TempDir(), "delete_self.sh")
		err = os.WriteFile(scriptFile, []byte(fmt.Sprintf("#!/bin/sh\nsleep 1\nrm -f \"%s\"", exePath)), 0755)
		if err != nil {
			fmt.Println("Error creating script file:", err)
			return
		}
		cmd = exec.Command(scriptFile)
	}

	// 启动删除命令
	err = cmd.Start()
	if err != nil {
		fmt.Println("Error starting delete command:", err)
		return
	}

	// 程序结束
}
